'''
Created on 06/04/2009

@author: Edward
'''
from yarra.datastore import dsconstants, dsofactory
from yarra.event import eventconstants
from yarra.event.event import Event
from yarra.event.eventhandler import BaseEventHandler
from yarra.event.eventmanager import EventManager
from yarra.logging import yarralogging
from yarra.datastore.dsstub import DSStub
import httplib
import os


class HubErrorHandler(BaseEventHandler):
    
    __logger = None
    
    def __init__(self):
        self.__logger = yarralogging.get_logger(DSStub().get_application_name())
        
    def do(self, data):
        dso = data
        http_request = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_HTTP_REQUEST).get_literal()
        lock = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_LOCK).get_literal()
        error_code = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_ERROR_CODE).get_literal()
        
        fault_message = None
        if error_code == httplib.NOT_FOUND:
            fault_message = "spear-im-not-active"
        elif error_code == httplib.REQUEST_TIMEOUT:
            fault_message = "hub-not-available"            
        else:
            self.__logger.error("Unhandled error code " + error_code)
            fault_message = "unknown-hub-error"

        relative_path = "../../../pages/im/imerror.html"
        
        # get the html template
        template_path = os.path.join(os.path.dirname(__file__), relative_path)
        file = open(template_path)
        html_template_string = file.read()
        html_string = html_template_string.replace('${fault_message}', fault_message)
        new_dso = dsofactory.create_dso_for_im_http_response_handler(httplib.OK, 
                                                               'text/html', 
                                                               html_string, 
                                                               http_request, 
                                                               lock)
        event = Event(eventconstants.HTTP_RESPONSE_EVENT_TYPE, new_dso)
        EventManager().add_event(event)                    